package com.emm.yixun.openapi.dto.base;

import java.util.List;

import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;
import net.sf.oval.configuration.annotation.AnnotationsConfigurer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.openapi.dto.exception.OvalUNCheckedException;

public class OvalUtil {
	private static Log logger = LogFactory.getLog(OvalUtil.class);

	@SuppressWarnings("unchecked")
	public static <T> T firstRealVal(T... objects) {
		for (Object object : objects) {
			if (object != null && !"".equals(object)) {
				return (T) object;
			}
		}
		return null;
	}

	public static String enumValues(Class<?> menum) {
		StringBuilder valstr = new StringBuilder();
		try {
			Object[] values;
			values = (Object[]) menum.getMethod("values").invoke(menum);
			valstr.append("[");
			String pre = "";
			for (int i = 0; i < values.length; i++) {
				valstr.append(pre + values[i].getClass().getMethod("getCode").invoke(values[i]));
				pre = ",";
			}
			valstr.append("]");
		} catch (Exception e) {
			logger.error("枚举反射取值", e);
		}
		return valstr.toString();
	}

	public static void validate(Object bean) {
		// 初始化
		Validator validator = new Validator(new AnnotationsConfigurer());
		Validator.setMessageResolver(new CustomResourceBundleMessageResolver("zh"));
		// 校验bean值是否合法
		List<ConstraintViolation> violations = validator.validate(bean);
		StringBuilder errormsg = new StringBuilder();
		errormsg.append("参数验证异常 : ");
		if (violations.size() > 0) {
			for (ConstraintViolation constraintViolation : violations) {
				errormsg.append(constraintViolation.getMessage().replaceAll(bean.getClass().getName() + ".", ""));
			}
			logger.error("参数code：" + XFUNExceptionCode.ILLEGAL_PARAMETER.getCode() + "，" + errormsg.toString());
			throw new OvalUNCheckedException(XFUNExceptionCode.ILLEGAL_PARAMETER.getCode(),
					XFUNExceptionCode.ILLEGAL_PARAMETER.getDesout());
		}
	}

}
